﻿using System;
using System.IO;
using System.Web;
using EPiServer.Core;
using log4net;

namespace TemplateFoundation.Handlers.JavaScriptTranslate
{
    /// <summary>
    /// EPiServer language manager used for creating JSON language objects based on EPiServer language files
    /// </summary>
    /// <remarks>All language files inside a folder called /lang/scripts will be included in script language objects</remarks>
    public sealed class ScriptLanguageManager
    {
        private static ILog _logger = LogManager.GetLogger(typeof(ScriptLanguageManager));

        private static readonly LanguageManager _instance;

        // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
        static ScriptLanguageManager()
        {
            try
            {
                var languageFolderPath = HttpContext.Current.Server.MapPath("/lang/scripts");

                if (!Directory.Exists(languageFolderPath))
                {
                    _logger.WarnFormat("[ETF] ScriptLanguageManager not initialized, folder {0} does not exist", languageFolderPath);

                    _instance = new LanguageManager();

                    return;
                }

                _instance = new LanguageManager(languageFolderPath);
            }
            catch (Exception ex)
            {
                _logger.Error("[ETF] Failed to initialize ScriptLanguageManager: " + ex.Message);
            }
        }

        ~ScriptLanguageManager()
        {
        }

        ScriptLanguageManager()
        {
        }

        public static LanguageManager Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}